let query = require('../../db/index');
let jwt = require('jsonwebtoken');
let config = require('../../jwtSecretKey');

exports.login = async (req, res) => {
    console.log(req.body);
    try {
        const { account, password } = req.body;
        let sql = `SELECT * FROM user WHERE account = '${account}'`;
        let result = await query(sql);

        if (result && result.length > 0) {
            // 用户存在，进行登录
            const user = result[0];
            console.log(user);
            if (user.password === password) {
                // 登录成功
                console.log('登录成功');
                const resUser = { id: user.id, name: user.name, account: user.account, avatar: user.avatar };
                const token = jwt.sign(resUser, config.jwtSecretKey, { expiresIn: config.jwtExpiresIn });
                res.dispatch(200, 'OK', { id: user.id, token: 'Bearer ' + token });
            } else {
                // 密码不匹配
                console.log('密码不正确');
                res.dispatch(401, 'Unauthorized', null);
            }
        } else {
            // 用户不存在，进行注册并登录
            console.log('用户不存在，进行注册');

            const { name, avatar } = req.body;

            // 在数据库中创建新用户
            let insertSql = `INSERT INTO user (account, password, name, avatar) VALUES ('${account}', '${password}', '${name}', '${avatar}')`;
            let insertResult = await query(insertSql);

            if (insertResult && insertResult.insertId) {
                // 注册成功后直接登录
                console.log('注册成功并登录');
                const resUser = { id: insertResult.insertId, account: account, name: name, avatar: avatar };
                const token = jwt.sign(resUser, config.jwtSecretKey, { expiresIn: config.jwtExpiresIn });
                res.dispatch(200, 'OK', { id: insertResult.insertId, token: 'Bearer ' + token });
            } else {
                // 注册失败
                console.log('注册失败');
                res.dispatch(500, 'Internal Server Error', null);
            }
        }
    } catch (err) {
        // 查询或注册出错
        console.error(err);
        res.dispatch(500, 'Internal Server Error', null);
    }
};
